import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class ThreadDemo9 {
    public static void main(String[] args) throws InterruptedException {
        //此处构造方法中写10，意思是有10个线程
        CountDownLatch latch = new CountDownLatch(10);
        //创建10个线程进行下载
        for (int i = 0; i < 10; i++) {
            int id = i;
            Thread t = new Thread(()->{
                Random random = new Random();
                int time = ((random.nextInt(5)+1)*1000);
                System.out.println("开始下载，线程:"+id);
                try {
                    Thread.sleep(time);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("结束下载，线程："+id);
                //告知latch我执行结束了
                latch.countDown();
            });
            t.start();
        }
        //通过这个来等待所有任务完成，也就是countDown被调用10次了
        latch.await();
        System.out.println("所有任务都执行完成了");
    }
}
